<?php

/**
 * 
 * ClientEngage: ClientEngage Visitor Voice (http://www.clientengage.com)
 * Copyright 2012, ClientEngage (http://www.clientengage.com)
 *
 * You must have purchased a valid license from CodeCanyon in order to have 
 * the permission to use this file.
 * 
 * You may only use this file according to the respective licensing terms 
 * you agreed to when purchasing this item on CodeCanyon.
 * 
 * 
 * 
 *
 * @author          ClientEngage <contact@clientengage.com>
 * @copyright       Copyright 2013, ClientEngage (http://www.clientengage.com)
 * @link            http://www.clientengage.com ClientEngage
 * @since           ClientEngage - Visitor Voice v 1.0
 * 
 */

/**
 * Utility class implementing basic descriptive statistics
 */
class Descriptives
{

    /**
     * Calculates and returns basic descriptive statistics
     * @param array $data Flat array of data to be processed
     * @return array Result array
     */
    public static function calc($data = array())
    {
        $result = array();

        sort($data);

        $result['count'] = count($data);
        $result['sum'] = array_sum($data);
        $result['min'] = min($data);
        $result['max'] = max($data);
        $result['range'] = $result['max'] - $result['min'];
        $result['mean'] = $result['sum'] / $result['count'];

        if (count($data) % 2 === 0)
        {
            $var = (count($data) - 1) / 2;
            $result['median'] = ($data[$var] + $data[$var + 1]) / 2;
        }
        else
        {
            $var = count($data) / 2;
            $result['median'] = $data[$var];
        }

        $valCount = array_count_values($data);
        arsort($valCount);
        $result['mode'] = current(array_keys($valCount));

        $varianceArray = array();
        foreach ($data as $num)
        {
            $varianceArray[] = pow($num - $result['mean'], 2);
        }
        if ($result['count'] > 1)
        {
            $result['var'] = array_sum($varianceArray) / ($result['count'] - 1);
            $result['stddev'] = sqrt($result['var']);
        }


        return $result;
    }

}